#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/cygwin.h>

char node_ver_maj[] = NODE_VER_MAJ;
char node_ver_min[] = NODE_VER_MIN;
char node_build[] = NODE_BUILD;

int main(int argc, char **argv)
{
	char basedir[256], home[256], line[2048], *dst, *src, *tag;
	FILE *in, *out;
	int prvch, slen, tlen, ch = 0;

	if (argc < 3) {
		fprintf(stderr, "usage: %s infile outfile\n", argv[0]);
		return 1;
	}
	cygwin_conv_to_full_win32_path("/home", home);
	sprintf(basedir, "%s\\entropy-%s.%s",
		home, node_ver_maj, node_ver_min);
	printf("Copying %s to %s patching for %s.%s-%s\nBasedir: %s\n",
		argv[1], argv[2],
		node_ver_maj, node_ver_min, node_build, basedir);

	in = fopen(argv[1], "rb");
	out = (0 == strcmp(argv[2], "-")) ? stdout : fopen(argv[2], "wb");
	dst = line;
	while (!feof(in)) {
		prvch = ch;
		ch = fgetc(in);

		if (-1 == ch)
			break;
		if (10 == ch) {
			if (13 != prvch) {
				*dst++ = 13;
			}
			*dst++ = 10;
			*dst = '\0';
			tag = "%BASEDIR%";
			src = basedir;
			tlen = strlen(tag);
			slen = strlen(src);
			while (NULL != (dst = strstr(line, tag))) {
				memmove(dst + slen, dst + tlen,
					strlen(dst + tlen) + 1);
				memcpy(dst, src, slen);
			}
			tag = "%NODE_VER_MAJ%";
			src = node_ver_maj;
			tlen = strlen(tag);
			slen = strlen(src);
			while (NULL != (dst = strstr(line, tag))) {
				memmove(dst + slen, dst + tlen,
					strlen(dst + tlen) + 1);
				memcpy(dst, src, slen);
			}
			tag = "%NODE_VER_MIN%";
			src = node_ver_min;
			tlen = strlen(tag);
			slen = strlen(src);
			while (NULL != (dst = strstr(line, tag))) {
				memmove(dst + slen, dst + tlen,
					strlen(dst + tlen) + 1);
				memcpy(dst, src, slen);
			}
			tag = "%NODE_BUILD%";
			src = node_build;
			tlen = strlen(tag);
			slen = strlen(src);
			while (NULL != (dst = strstr(line, tag))) {
				memmove(dst + slen, dst + tlen,
					strlen(dst + tlen) + 1);
				memcpy(dst, src, slen);
			}
			fwrite(line, 1, strlen(line), out);
			dst = line;
		} else {
			*dst++ = ch;
		}
	}
	if (0 != strcmp(argv[2], "-")) {
		fclose(out);
	}
	fclose(in);
	return 0;
}
